package com.android.demo.widget;

import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public final class StartForResults {
	/**
	 * 调用系统相册 或是 摄像头 获取图片数据
	 * 	用法：
	 * 	// 摄像头
		StartForResults.getPicFromCamera(DynamicCommentActivity.this);
		// 相册
		StartForResults.getPicFromAlbum(DynamicCommentActivity.this);
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode,
				Intent paramIntent) {
			//获取图片数据
			switch (requestCode) {
			// 图片上传
			case StartForResults.CAMERA_PICKED_WITH_DATA:
			case StartForResults.PHOTO_PICKED_WITH_DATA:
				PickData mData = StartForResults.onRresult(this, requestCode,resultCode, paramIntent);
		}
			
		}
	 * */
	public final static int PHOTO_PICKED_WITH_DATA = 1;
	public final static int CAMERA_PICKED_WITH_DATA = 2;
	public final static String TAG = "StartForResults";

	// get photo from album
	public static void getPicFromAlbum(Activity activity) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				MediaStore.Images.Media.CONTENT_TYPE);
		try {
			activity.startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);// 启动相册
		} catch (ActivityNotFoundException e) {
		}
	}
	
	// view photo from album
	public static void viewPicFromAlbum(Activity activity, String loadpath) {

		Intent intent = new Intent("android.intent.action.VIEW");

		intent.addCategory("android.intent.category.DEFAULT");

		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		Uri uri = Uri.fromFile(new File(loadpath));

		intent.setDataAndType(uri, "image/*");
		
		activity.startActivity(intent);
	}

	// get photo from camera
	public static void getPicFromCamera(Activity activity) {
		// set camera intent
		Intent localIntent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

		// temp file
		File dir = Environment.getExternalStorageDirectory();
		File localTemp = new File(dir, "camera-t.jpg");

		Uri localUri = Uri.fromFile(localTemp);
		localIntent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
		localIntent.putExtra( MediaStore.EXTRA_VIDEO_QUALITY,100);

		activity.startActivityForResult(localIntent, CAMERA_PICKED_WITH_DATA);
	}

	public static class PickData {
		public Bitmap thumbBmp;
		public String localPath;
		public String title;
		
		//type:1 = GIF，2 = JPG，3 = PNG
		public int type;
		public long size;
		public int width;
		public int height;
		public PickData(){
		}
		public PickData(String lp){
			localPath = lp;
			type = getSuffixInt(localPath);
			title = new File (localPath).getName();
			thumbBmp = getLocalBitmap(localPath, 60, this);
		}
	}
	
	public static PickData onRresult(Activity activity, int requestCode,
			int resultCode, Intent paramIntent) {
		/***/Log.i(TAG, "requestCode" + requestCode + "|resultCode" + resultCode
				+ "|" + paramIntent);

		PickData pickData = null;
		
		if (resultCode != Activity.RESULT_OK)
			return pickData;
		
		pickData = new PickData();
		
		Uri photoUri = null;
		if (paramIntent != null)
			photoUri = paramIntent.getData();
		switch (requestCode) {
			// pick photo from album
		case StartForResults.PHOTO_PICKED_WITH_DATA:
			break;
			// pick photo from camera
		case StartForResults.CAMERA_PICKED_WITH_DATA:
			try {
				// 获取 拍照临时文件
				File sdDir = Environment.getExternalStorageDirectory();
				String tempPicName = "camera-t.jpg";
				File tempPic = new File(sdDir, tempPicName);
				
				photoUri = Uri.parse(MediaStore.Images.Media.insertImage(
						activity.getContentResolver(), tempPic
								.getAbsolutePath(), null, null));

				tempPic.delete();
			} catch (Exception localException) {
			}
			break;
		}
		
		// get path
		pickData.localPath = getLocalPath(photoUri, activity);
		if (pickData.localPath.length() == 0) return null;
		
		// get title
		pickData.title = new File (pickData.localPath).getName();
		// get size
		//pickData.size = getFileSize(pickData.localPath);
		// get thumbBmp , width , height
		pickData.thumbBmp = getLocalBitmap(pickData.localPath, 300, pickData);
		if (pickData.thumbBmp ==null ) return null;
		
		// get type
		pickData.type = getSuffixInt(pickData.localPath);
		
		if (pickData.type==-1) return null;

		/***/Log.i(TAG, "path size"+pickData.size+ "path LocalPath"+pickData.localPath+pickData.thumbBmp.getWidth()+"-"+pickData.thumbBmp.getHeight());
		/**
		if (false) {
			try {
				Bitmap bmp = MediaStore.Images.Media.getBitmap(activity
						.getContentResolver(), photoUri);
				Log.i(TAG, "origin bmp:" + bmp.getWidth() + "-"
						+ bmp.getHeight());
			} catch (Exception e) {

			}
		}*/
		return pickData;
	}

	public static String getSuffix(String url){
		int index = url.lastIndexOf(".");
		
		if (index>0&&index<url.length()-1) {
			String typeStr = url.substring(index+1);
			return typeStr.toLowerCase();
		}
		
		return ""; 
	}
	
	public static int getSuffixInt(String url){
		//type:1 = GIF，2 = JPG，3 = PNG
		String typeStr = getSuffix(url);
		int type = -1;
		if (typeStr.equalsIgnoreCase("gif")) {
			type = 1;
		}
		
		if (typeStr.equalsIgnoreCase("jpg")) {
			type = 2;
		}
		
		if (typeStr.equalsIgnoreCase("png")) {
			type = 3;
		}
		return type;
	}
	
	public static Bitmap getLocalBitmap(String path, int size , PickData inoutData) {
		BitmapFactory.Options options = new BitmapFactory.Options();

		options.outHeight = size;

		options.inJustDecodeBounds = true;

		// 获取这个图片的宽和高
		Bitmap bm = BitmapFactory.decodeFile(path, options); //此时返回bm为空
		
		options.inJustDecodeBounds = false;
		
		inoutData.height = options.outHeight;
		inoutData.width = options.outWidth;
		int be = options.outHeight / (int)(size/10);
		if(be%10 !=0) 
			be+=10;

		be=be/10;
		if (be <= 0)
			be = 1;

		options.inSampleSize = be;
		bm = BitmapFactory.decodeFile(path, options);
		Log.i(TAG, "getLocalBitmap width " + bm.getWidth() + " height " + bm.getHeight());
		
		return bm;
	}
	
//	private static long getFileSize(String path){
//		File file = new File(path);
//		return file.length();
//	}
	
	private static String getLocalPath(Uri uri, Activity activity) {
		String path = "";
		// 获取文件的绝对路径
		String[] projection = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE };
		Cursor cursor = MediaStore.Images.Media.query(activity
				.getContentResolver(), uri, projection);
		if (cursor != null && cursor.moveToNext()) {
			path = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
		}
		return path;
	}
}
